package com.android.nearshop.app.activity.shop;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.common.LoadableActivity;
import com.android.nearshop.app.activity.map.ShopLocationActivity;
import com.android.nearshop.app.adapter.listadapter.CommontListAdapter;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.model.Addr;
import com.android.nearshop.io.database.ShopDB;
import com.android.nearshop.io.protocol.ProtocolManager;
import com.android.nearshop.io.protocol.in.ShopDetailAction;
import com.android.nearshop.io.protocol.in.SoapAction.ActionListener;
import com.android.nearshop.io.protocol.out.Comment;
import com.android.nearshop.io.protocol.out.ShopDetail;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.ImageLoader;
import com.android.nearshop.util.ImageLoader.Imager;
import com.android.nearshop.util.Log;

/**
 * 商家详细
 * @author huangyue
 *
 */
public class ShopDetailActivity extends LoadableActivity implements OnClickListener
{
	private ShopDetailAction mShopDetailAction;
	private ShopDetail mShopDetail;
	private PopupWindow selLocPopWin;
	private int shopId;
	private String discount;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_shop_detail);
		
		Intent intent = getIntent();
		shopId = intent.getIntExtra(Constant.TAG_DETAIL_SHOPID, -1);
		discount = intent.getStringExtra(Constant.TAG_DISCOUNT);
		
		loadData();
	}

	private void loadData()
	{
	    mLoadingView.showLoadingView();
	    if (MyApplication.getContext().isNetWorkAvailable()) 
        {
            online(shopId, discount);
        } else {
            mShopDetail = ShopDB.find(shopId);
            if(mShopDetail == null)
            {
                mLoadingView.showLoadingErrView(R.string.no_result, false);
            }else
            {
                initView();
            }
        }
	}
	
	private int errorTime = 0;
	
	@Override
	public void refreshView()
	{
	    loadData();
	}
	
	private void online(int shopId, final String discount) {
		mShopDetailAction = new ShopDetailAction(shopId, 1);
		mShopDetailAction.setActionListener(new ActionListener<ShopDetail>() {

			@Override
			public void onSucceed(ShopDetail viewHolder) {
				mShopDetail = viewHolder;
				mShopDetail.discount = discount;
				ShopDB.saveShop(mShopDetail);
				initView();
			}

			@Override
			public void onError(int resultCode) {
				Log.e("ShopDetailActivity", "resultCode = " + resultCode);
				
				if(!MyApplication.getContext().isNetWorkAvailable()){
					mLoadingView.showNetErrView(false);
				}
				
				if(errorTime == 2){
					mLoadingView.showLoadingErrView(false);
					return;
				}
				
				ProtocolManager.getProtocolManager().submitAction(mShopDetailAction);
				errorTime++;
			}
		});
		ProtocolManager.getProtocolManager().submitAction(mShopDetailAction);
	}
	
	private void initView() 
	{
	    mLoadingView.showMainView();
	    
		ImageView image = (ImageView) findViewById(R.id.detail_icon);
		// 缓存图片[zhaohua]
		ImageLoader.getInstance().DisplayImage(
		        new Imager(mShopDetail.shopAdvPic, image, 97, R.drawable.default_detail_pic));
		
		TextView temp = (TextView)findViewById(R.id.detail_shop_name);
		temp.setText(mShopDetail.shopName);
		
		if(mShopDetail.catalogyName != null){
			temp = (TextView)findViewById(R.id.detail_shop_catalogyname);
			temp.setText(getString(R.string.category_format, mShopDetail.catalogyName));
		}
		
		RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar_recommend);
		ratingBar.setRating((float) mShopDetail.recommend);
		
		temp = (TextView) findViewById(R.id.discount_text);
		if(mShopDetail.discountdetail != null && !"".equals(mShopDetail.discountdetail)){
			temp.setText(mShopDetail.discountdetail);
		} else {
			temp.setText(R.string.none);
		}
		
		temp = (TextView) findViewById(R.id.club_day_text); 
		if(mShopDetail.weekContent != null && !"".equals(mShopDetail.weekContent)){
			temp.setText(mShopDetail.weekContent);
		} else {
			temp.setText(R.string.none);
		}
		
		temp = (TextView) findViewById(R.id.addr_text);
		if(mShopDetail.shopAdd != null && !"".equals(mShopDetail.shopAdd)){
			temp.setText(mShopDetail.shopAdd);
		}else {
			temp.setText(R.string.none);
		}
		
		temp = (TextView) findViewById(R.id.tax_text);
		if(mShopDetail.shopPhone != null && !"".equals(mShopDetail.shopPhone)){
			temp.setText(mShopDetail.shopPhone);
		}else {
			temp.setText(R.string.none);
		}
		
		if(mShopDetail.scoreCount != null && mShopDetail.scoreCount.length == 3)
		{
    		temp = (TextView) findViewById(R.id.comment_good);
    		temp.setText(getString(R.string.comment_good, mShopDetail.scoreCount[0]));
    		
    		temp = (TextView) findViewById(R.id.comment_normal);
    		temp.setText(getString(R.string.comment_normal, mShopDetail.scoreCount[1]));
    		
    		temp = (TextView) findViewById(R.id.comment_bed);
    		temp.setText(getString(R.string.comment_bed, mShopDetail.scoreCount[2]));
		}
		
		findViewById(R.id.shop_addr_lay).setOnClickListener(this);
		findViewById(R.id.shop_tax_lay).setOnClickListener(this);
		findViewById(R.id.shop_detail_lay).setOnClickListener(this);
		
		if(mShopDetail.commentList != null && mShopDetail.commentList.size() > 0) {
			Comment comment = mShopDetail.commentList.get(0);
			
			temp = (TextView) findViewById(R.id.comment_name);
			if(comment.cmmTitle == null || comment.cmmTitle.length() == 0){
				temp.setText(R.string.commont_no_name);
			} else {
				temp.setText(comment.cmmTitle);
			}
			
			temp = (TextView) findViewById(R.id.comment_text);
			temp.setText(comment.cmmContent);
			
//			ImageView imagetView = (ImageView) findViewById(R.id.comment_level_icon);
//			imagetView.setImageResource(CommontListAdapter.souce[comment.score]);
			
			findViewById(R.id.commot_info).setOnClickListener(this);
		}  else {
			findViewById(R.id.commot_info).setVisibility(View.GONE);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		dissPop();
	}
	
	@Override
	protected void setupTitleBar(TitleBar titleBar) {
		titleBar.setLeftImage(0);
		titleBar.setRigthImage(0);
//		titleBar.setRightVisible(false);
		titleBar.setRigthText(R.string.map_text);
		titleBar.setTitle(R.string.shop_detail);
		
		titleBar.setOnTitleClickListener(new OnTitleClickListener() {
			
			public void onRightClick() {
				if(mShopDetail == null){
					return;
				}
				// 地址到地图
                ShopLocationActivity.startActivity(ShopDetailActivity.this, new Addr(mShopDetail.lon,mShopDetail.lat,mShopDetail.shopName));
			}
			
			public void onLeftClick() {
				finish();
			}
		}, true, true);
	}
	
    private void showSelLocPopWin(String[] nums)
    {
        if(selLocPopWin == null)
        {
            View contentView  = LayoutInflater.from(this).inflate(R.layout.popview_tax_select, null);
            selLocPopWin = new PopupWindow(contentView,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT, true);            
            selLocPopWin.setBackgroundDrawable(new BitmapDrawable());
            selLocPopWin.setFocusable(true);
            selLocPopWin.setTouchable(true);
            
            ListView list = (ListView) contentView.findViewById(R.id.tax_list);
            TextView cancel = (TextView) contentView.findViewById(R.id.pop_cancel);
            cancel.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    dissPop();
                }
            });
            list.setAdapter(new TaxAdapter(this, 0, nums));
        }

        selLocPopWin.showAtLocation(getWindow().getDecorView(),Gravity.BOTTOM, 0, 0);
    }
    
    private class TaxAdapter extends ArrayAdapter<String> implements OnClickListener{
    	private String[] nums;
		public TaxAdapter(Context context, int textViewResourceId,
				String[] objects) {
			super(context, textViewResourceId, objects);
			nums = objects;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = LayoutInflater.from(ShopDetailActivity.this).inflate(R.layout.list_item_tax, null);
			}
			if(nums[position].length() == 8){
				nums[position] = "0769" + nums[position];
			}
			((TextView)convertView.findViewById(R.id.tax_num)).setText(nums[position]);
			convertView.setTag(nums[position]);
			convertView.findViewById(R.id.call_button).setTag(nums[position]);
			convertView.setOnClickListener(this);
			convertView.findViewById(R.id.call_button).setOnClickListener(this);
			return convertView;
		}

		@Override
		public void onClick(View v) {
			Intent it = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + (String)v.getTag()));
			startActivity(it);
		}

    	
    }
    
    
    private void dissPop()
    {
        if(selLocPopWin != null && selLocPopWin.isShowing())
        {
            selLocPopWin.dismiss();
        }
    }
    

    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.shop_addr_lay:
            {
                // 地址到地图
                ShopLocationActivity.startActivity(this, new Addr(mShopDetail.lon,mShopDetail.lat,mShopDetail.shopName));
                break;
            }
            case R.id.shop_tax_lay:
            {
            	String nums = ((TextView)v.findViewById(R.id.tax_text)).getText().toString();
            	if(nums != null){
            		showSelLocPopWin(nums.split(" ,"));
            	}
            	break;
            }
            case R.id.shop_detail_lay:
            {
            	if(mShopDetail.content == null){
            		break;
            	}
            	
            	Intent intent = new Intent();
            	intent.setClass(getApplicationContext(), ShopInfoActivity.class);
            	intent.putExtra(Constant.TAG_DETAIL_SHOPIMAGE, mShopDetail.shopAdvPic);
            	intent.putExtra(Constant.TAG_DETAIL_SHOPCONTENT, mShopDetail.content);
            	
            	startActivity(intent);
            	break;
            }
            case R.id.commot_info:
            {
            	Intent intent = new Intent();
            	intent.setClass(getApplicationContext(), CommontActivity.class);
            	intent.putExtra(Constant.TAG_DETAIL_SHOPID, mShopDetail.shopId);
            	
            	startActivity(intent);
            	break;
            }
        }
    }
}
